package com.itheima.dubbo.api.mongo.impl;

import com.itheima.dubbo.api.mongo.VisitorsApi;
import com.tanhua.model.mongo.Visitors;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class VisitorsApiImpl implements VisitorsApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    //保存或者更新访客记录
    @Override
    public void saveOrUpdate(Visitors visitors) {
        Query query = new Query(Criteria.where("userId").is(visitors.getUserId()).and("visitorUserId").is(visitors.getVisitorUserId()).and("visitDate").is(visitors.getVisitDate()));
        if(!mongoTemplate.exists(query,Visitors.class)){
            //不存在该访客记录则保存
            mongoTemplate.save(visitors);
        }else{
            //如果已经存在则更新
            Update update = new Update();
            update.set("date",System.currentTimeMillis());
            mongoTemplate.updateFirst(query,update,Visitors.class);
        }

    }


    //查看最近的访客
    @Override
    public List<Visitors> queryVisitors(Long userId, Long lastTime) {
        Criteria criteria = Criteria.where("userId").is(userId);
        if(lastTime!=null){
            criteria.and("date").gt(lastTime);
        }
        Query query = new Query(criteria);
        query.with(Sort.by(Sort.Order.desc("date")));
        query.limit(5);
        List<Visitors> visitorsList = mongoTemplate.find(query, Visitors.class);
        return visitorsList;
    }
}
